<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding:0;
      list-style: none;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="400" height="400"></canvas>
  <script>
    /** @type {HTMLCanvasElement} */
    var balls=[]
    var canvas=document.querySelector("#canvas")
    var ctx=canvas.getContext("2d")
    var img=new Image()
    // img.crossOrigin=""//解决跨域
    img.crossOrigin = 'Annoymous'
    // img.src="./img/001.jpg"//本地图片不行！！！
    img.src="https://c-ssl.duitang.com/uploads/item/201907/22/20190722171500_fshfb.thumb.1000_0.jpg"
    function Ball(x,y,color){
      this.x=x
      this.y=y
      this.color=color
      this.draw=function(){
        ctx.beginPath()
        ctx.save()
        ctx.fillStyle=this.color
        ctx.arc(this.x,this.y,1,0,Math.PI*2)
        ctx.fill()
        ctx.restore()
        ctx.closePath()
      }
    }
    img.onload=function(){
      ctx.drawImage(img,0,0,400,400)
      let tp=ctx.getImageData(0,0,400,400)
      // console.log(canvas.width);
      // console.log(tp.data);//√
      // console.log(tp);
      ctx.clearRect(0,0,canvas.width,canvas.height)
      for(var i=0;i<tp.data.length;i+=16){
        // console.log(i/4);
        let x=i/4%canvas.width
        console.log(x);
        let y=i/4/canvas.width|0+2
        // console.log(y);
        let r=tp.data[i]
        let g=tp.data[i+1]
        let b=tp.data[i+2]
        let a=tp.data[i+3]
        let rgba="rgba("+r+","+g+","+b+","+a+")"
        // console.log(rgba);
        let ball=new Ball(x,y,rgba)
        balls.push(ball)
        // console.log("rgba("+r+","+g+","+b+","+a+")");
      // tp.data[i]=225
      // tp.data[i+1]=0
      // tp.data[i+2]=0
      // tp.data[i+3]=225
      }
      drawh()
      // ctx.putImageData(tp,0,0)
    }
    function drawh(){
      for(let j=0;j<balls.length;j++){
        balls[j].draw()
      }
    }
  </script>
</body>
</html>